<template>
  <div class="page">
    <van-nav-bar :title="`${ modify ? '添加' : '添加' }角色`" left-arrow @click-left="goBack"/>
    <van-form class="page-content" :disabled="btnLoading" @submit="submit">
      <van-field v-if="info.userId" readonly label="上级id" :value="info.pid"/>
      <van-field v-if="info.userId" readonly label="用户id" :value="info.userId"/>

      <form-picker :rules="[ $check('', true) ]" required label="角色类型" v-model="info.roleType" :option="option.roleType"/>
      <van-field :rules="[ $check('', true), $check('用户名称只能输入1-20位英文数字汉字', 'text20') ]" required label="用户名称" v-model="info.nick" placeholder="请输入"/>
      <van-field :rules="[ $check('', true), $check('用户账号只能输入1-20位英文数字汉字', 'text20') ]" required label="用户账号" v-model="info.userName" placeholder="请输入"/>
      <van-field :rules="[ $check('', 'phone') ]" required label="绑定手机" v-model="info.userPhone" placeholder="请输入">
        <form-button slot="button" size="small" type="info" @click="sms.send" :disabled="btnLoading" :loading="sms.loading" v-if="!modify">{{ sms.string }}</form-button>
      </van-field>     
      <van-field :rules="[ $check('', true) ]" required label="短信验证码" v-model="sms.code" placeholder="请输入" v-if="!modify"/>
      <van-field :rules="[ $check('', true) ]" type="password" required label="登录密码" v-model="info.password" v-if="!modify" placeholder="请输入"/>
      
      <!-- 业务员 和 服务商不需要分成部分 -->
      <template v-if="info.roleType && info.roleType !== 2 && info.roleType !== 4">
        <form-picker :rules="[ $check('', true) ]" required label="加盟方式" v-model="info.joinWay" :option="option.joinWay"/>
        <form-picker :rules="[ $check('', true) ]" required label="分成方式" v-model="info.proportionWay" :option="option.proportionWay"/>
        <form-picker :rules="[ $check('', true) ]" required label="分成基础" v-model="info.divideType" :option="option.divideType"/>
        <van-field :rules="[ $check('请输入数字', 'number'), $check('请输入0-100', 'n100') ]" required v-model="info.virtualProportion" label="设备摊销" placeholder="请输入提成比例"/>
        <van-field :rules="[ $check('请输入数字', 'number'), $check('请输入0-100', 'n100') ]" required v-model="info.dailyEquipmentCost" label="日常设备成本" placeholder="请输入日常设备成本"  v-if="info.proportionWay == 1"/>
        <van-field :rules="[ $check('请输入数字', 'number'), $check('请输入0-100', 'n100') ]" required v-model="info.realProportion" label="系统参数" placeholder="请输入系统参数" v-if="(roleType == 0 || shareType == 0) && info.divideType == 1 && info.roleType == 3"/>
      </template>
      <!-- 服务商的提成比例 -->
      <van-field :rules="[ $check('请输入数字', 'number'), $check('请输入0-100', 'n100') ]" v-if="info.roleType == 4" v-model="info.virtualProportion" required label="提成比例" placeholder="请输入提成比例"/>
      <!-- 状态 -->
      <form-picker :rules="[ $check('', true) ]" required label="状态" v-model="info.status" :option="option.status"/>

      <!-- 弹出宝权限 买宝权限 admin给代理才能开 -->
      <template v-if="roleType == 0 && info.roleType == 1">
        <form-picker :rules="[ $check('', true) ]" required label="弹出宝权限" v-model="info.popupPower" :option="option.trueFalse"/>
        <form-picker :rules="[ $check('', true) ]" required label="借宝权限" v-model="info.lend" :option="option.trueFalse"/>
        <form-picker :rules="[ $check('', true) ]" required label="买宝钱获取权" v-model="info.delayingPurchases" :option="option.falseTrue"/>
        <van-field :rules="[ $check('请输入数字', 'number'), $check('请输入0-99', 'n99') ]" required label="买宝分成" v-model="info.chargerMoney" placeholder="请输入买宝钱金额" v-if="info.delayingPurchases == 1"/>
        <form-picker :rules="[ $check('', true) ]" required label="分成权限" v-model="info.shareType" :option="option.trueFalse"/>
      </template> 

      <div style="margin: 1rem 16px 16px;">
        <van-button block type="info" :loading="btnLoading">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {
        chargerMoney: '',
        pid: '',
        handlersRoleType: '',
        handlerUserId: '',
        roleType: '',
        userName: '',
        joinWay: 0,
        realProportion: '',
        proportionWay: 0,
        dailyEquipmentCost: '',
        status: 0,
        divideType: 1,
        virtualProportion: '',
        userPhone: '',
        password: '',
        nick: '',
        shareType: 1,
        popupPower: 1,
        delayingPurchases: 1,
        lend: 1
      },
      btnLoading: false,

      modify: false,
      roleType: this.$store.state.userInfo.roleType,
      shareType: this.$store.state.userInfo.shareType,

      option: {
        roleType: [
          { value: 1, label: '代理' },
          { value: 2, label: '业务员' },
          { value: 3, label: '商户' },
          { value: 4, label: '服务商' }
        ],
        proportionWay: [
          { value: 0, label: '比例分成' },
          { value: 1, label: '非比例分成' }
        ],
        joinWay: [
          { value: 0, label: '购买' },
          { value: 1, label: '投放' }
        ],
        status: [
          { value: 0, label: '正常' },
          { value: 1, label: '禁用' }
        ],
        divideType: [
          { value: 1, label: '绝对分成' },
          { value: 2, label: '相对分成' }
        ],
        trueFalse: [
          { value: 0, label: '是' },
          { value: 1, label: '否' }
        ],
        falseTrue: [
          { value: 0, label: '否' },
          { value: 1, label: '是' }
        ]
      },

      sms: {
        code: '',
        loading: false,
        string: '获取验证码',
        timer: null,
        send: () => {
          if (this.sms.string != '获取验证码') return ;
          let reg = this.$check('请输入正确的手机号码', 'phone');
          if (!reg.pattern.test(this.info.userPhone)) return this.$toast(reg.message);
          this.sms.loading = true;
          this.$axios.get('/api/SmsController/sendverifyCode', { 
            phoneNumber: this.info.userPhone 
          }).then(res => {      
            this.$toast('短信验证码发送成功！')
            this.sms.loading = false;
            this.sms.string = 60;
            this.sms.timer = setInterval(() => {
              this.sms.string--;
              if (this.sms.string == 0) {
                this.sms.string = '发送验证码';
                clearInterval(this.sms.timer);
                this.sms.timer = null;
              }
            }, 1000);
          }).catch(() => {
            this.sms.loading = false;
          })
        }
      }
    };
  },
  methods: {
    submit() {
      
      let obj = JSON.parse(JSON.stringify(this.info));
      // if(obj.userName === '') return this.$toast('请输入用户账号');
      // if(!/^([a-zA-Z0-9\u4e00-\u9fa5]){1,20}$/.test(obj.userName)) return this.$toast('用户账号只能输入1-20位英文数字汉字');
      // if(obj.userPhone === '') return this.$toast('请输入绑定手机');
      // if(obj.password === '') return this.$toast('请输入登录密码');
      // if(obj.roleType !== '业务员') {
      //   if(obj.joinWay === '') return this.$toast('请选择加盟方式');
      //   if(obj.proportionWay === '') return this.$toast('请选择分成方式');
      //   if(obj.virtualProportion === '') return this.$toast('请输入提成比例');
      //   if(!/^([1-9]?\d|100)$/.test(obj.virtualProportion)) return this.$toast('提成比例只能为0-100之间的整数');
      //   if(obj.proportionWay==='非比例分成'&&obj.dailyEquipmentCost === '') return this.$toast('请输入日常设备成本');
      //   if(obj.dailyEquipmentCost!==''&&!/^[1-5]$/.test(obj.dailyEquipmentCost)) return this.$toast('日常设备成本只能为1-5之间的整数');
      //   if(obj.realProportion!==''&&!/^([1-9]?\d|100)$/.test(obj.realProportion)) return this.$toast('系统参数只能为0-100之间的整数');
      // } else {
      //   obj.virtualProportion = 0;
      // }
      // if(obj.status === '') return this.$toast('请选择状态');
      // if(this.sms === ''&&(!this.modify)) return this.$toast('请输入验证码');
      this.btnLoading = true;
      if (obj.chargerMoney) {
        if (isNaN(obj.chargerMoney)) {
          this.$toast('买宝分成需要输入数字');
          return ;
        } else if (obj.chargerMoney > 99 || obj.chargerMoney < 0) {
          this.$toast('买宝分成需要大于0，小于99');
          return ;
        }
      }
      if(!this.modify) {
        this.$axios.get('/api/SmsController/checkSmsCode', { 
          phoneNumber: obj.userPhone, code: this.sms.code
        }).then(() => {
          this.submitFun();
        }).catch(() => {
          this.btnLoading = false;
        });
      } else {
        this.submitFun();
      }
    },
    submitFun() {
      let obj = JSON.parse(JSON.stringify( this.info ));
      // obj.popupPower = this.picker.popupPowerColumns.find((v: any) => v.text === obj.popupPower).value;
      // obj.lend = this.picker.lendColumns.find((v: any) => v.text === obj.lend).value;
      // 非admin并且无分成权限，真实参数和虚拟参数相同
      if (!(this.roleType === 0 || this.shareType === 0) ) obj.realProportion = obj.virtualProportion;
      // 代理和服务商，真真实参数和虚拟参数相同
      if (obj.roleType == 4 || obj.roleType == 1) obj.realProportion = obj.virtualProportion;
      if (obj.divideType == 2) obj.realProportion = obj.virtualProportion;

      // 上传的时候phone设置为userPhone
      obj.phone = obj.userPhone;

      // 所有对象必传值
      obj.handlerUserId = this.$store.state.userInfo.userId;
      obj.handlersRoleType = this.$store.state.userInfo.roleType;

      this.$axios.post('/api/roleController/addRoleModel', obj).then(res => {
        this.$toast(`${ this.modify ? '修改' : '新增' }成功！`);
        this.btnLoading = false;
        this.$router.go( -1 );
      }).catch(() => {
        this.btnLoading = false;
      })
    },
    setValue(info) {
      let obj = JSON.parse(JSON.stringify(info));
      if (!obj.divideType) obj.divideType = 1;
      if (obj.divideType == 2) obj.realProportion = obj.virtualProportion;
      obj.userPhone = obj.phone;
      obj.dailyEquipmentCost = obj.dailyEquipmentCost || '';
      delete obj.phone;

      this.info = obj;
      this.modify = true;
    },
    goBack() {
      if (this.modify) {
        this.$emit('close');
      } else {
        this.$router.go(-1);
      }
    }
  },
  mounted() { 
    if (this.$store.getters.ifSales) {
      this.option.roleType = [{ value: 3, label: '商户' }];
      this.info.roleType = 3;
    }
    this.info.pid = this.$store.state.userInfo.userId;
  },
  beforeDestroy() {
    if (this.sms.timer) clearInterval(this.sms.timer);
  }
};
</script>